import { createRouter, createWebHistory } from 'vue-router'
import Login from '../views/Login.vue'
import LotterySelect from '../views/LotterySelect.vue'
import LotteryApp from '../views/LotteryApp.vue'
import { ElMessage } from 'element-plus'

const routes = [
  {
    path: '/',
    name: 'Login',
    component: Login
  },
  {
    path: '/select',
    name: 'LotterySelect',
    component: LotterySelect,
    meta: { requiresAuth: true }
  },
  {
    path: '/lottery/:type',
    name: 'LotteryApp',
    component: LotteryApp,
    meta: { requiresAuth: true },
    props: true
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 路由守卫 - 修改为检查userInfo中的token
router.beforeEach((to, from, next) => {
  console.log(to.matched, 'to.matched');

  if (to.matched.some(record => record.meta.requiresAuth)) {
    try {
      // 获取本地存储的userInfo
      const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')
      // 验证userInfo是否存在且包含有效token
      if (!userInfo || !userInfo.token) {
        ElMessage.error('登录信息已过期，请重新登录')
        next('/')
      } else {
        next()
      }
    } catch (error) {
      // 解析JSON出错时视为未登录
      ElMessage.error('登录信息已过期，请重新登录')
      next('/')
    }
  } else {
    next()
  }
})

export default router